package com.yuexia.yxim.server.processer;

import com.yuexia.yxim.common.bean.msg.ProtoMsg;
import com.yuexia.yxim.common.bean.msg.User;
import com.yuexia.yxim.common.enums.ProtoInstant;
import com.yuexia.yxim.server.protoBuilder.LoginResponceBuilder;
import com.yuexia.yxim.server.server.ServerSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Service;

/**
 * @Author: yue_xia
 * @Date: 2020/6/2 10:04 下午
 */
@Service
public class LoginProcesser extends AbstractServerProcesser{

    @Autowired
    private LoginResponceBuilder loginResponceBuilder;

    @Override
    public ProtoMsg.HeadType type() {
        return ProtoMsg.HeadType.LOGIN_REQUEST;
    }

    //登录的逻辑
    @Override
    public boolean action(ServerSession session, ProtoMsg.Message pkg) {

        //取出token验证
        ProtoMsg.LoginRequest loginRequest = pkg.getLoginRequest();
        long sequence = pkg.getSequence();

        User user = User.fromMsg(loginRequest);

        //检查用户
        Boolean isValidUser = chaeckUser(user);
        if (!isValidUser) {
            ProtoInstant.ResultCodeEnum resultCodeEnum = ProtoInstant.ResultCodeEnum.NO_TOKEN;

            //生成登录失败的报文
            ProtoMsg.Message responce = loginResponceBuilder.loginResponce(resultCodeEnum, sequence, "-1");
            session.writeAndFlush(responce);
            return false;
        }

        session.setUser(user);
        session.bind();
        //登录成功
        ProtoInstant.ResultCodeEnum successEnum = ProtoInstant.ResultCodeEnum.SUCCESS;
        //生成登录成功的报文
        ProtoMsg.Message responce = loginResponceBuilder.loginResponce(successEnum, sequence, session.getSessionId());

        //发送报文
        session.writeAndFlush(responce);
        return true;
    }

    private Boolean chaeckUser(User user) {

        //校验用户,比较耗时的操作,需要100 ms以上的时间
        //方法1：调用远程用户restfull 校验服务
        //方法2：调用数据库接口校验

        return true;
    }
}
